package org.xx.armory.config.log4j2;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.logging.log4j.Level;

import static org.apache.logging.log4j.Level.ALL;
import static org.apache.logging.log4j.Level.DEBUG;
import static org.apache.logging.log4j.Level.ERROR;
import static org.apache.logging.log4j.Level.FATAL;
import static org.apache.logging.log4j.Level.INFO;
import static org.apache.logging.log4j.Level.OFF;
import static org.apache.logging.log4j.Level.TRACE;
import static org.apache.logging.log4j.Level.WARN;

public class LevelConverter
        implements Converter {

    /**
     * {@inheritDoc}
     */
    @Override
    public <T> T convert(
            Class<T> clazz,
            Object o
    )
            throws ConversionException {
        if (o == null) {
            return null;
        }
        if (clazz != Level.class) {
            throw new ConversionException("cannot convert " + o + " to " + clazz);
        }
        if (!(o instanceof CharSequence)) {
            throw new ConversionException("cannot convert " + o + " to " + clazz);
        }

        final String s = o.toString().trim().toUpperCase();
        switch (s) {
            case "ALL":
                return clazz.cast(ALL);
            case "TRACE":
                return clazz.cast(TRACE);
            case "DEBUG":
                return clazz.cast(DEBUG);
            case "INFO":
                return clazz.cast(INFO);
            case "WARN":
                return clazz.cast(WARN);
            case "ERROR":
                return clazz.cast(ERROR);
            case "FATAL":
                return clazz.cast(FATAL);
            case "OFF":
                return clazz.cast(OFF);
            default:
                throw new ConversionException("cannot convert " + o + " to " + clazz);
        }
    }
}
